package com.algorithm;

/**
 * 移除链表的倒数第n个节点
 */
public class RemoveNthNode {


    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode headNode=new ListNode();
        headNode.next=head;
        ListNode n1=headNode;
        ListNode n2=headNode;

        for (int i=0;i<=n;i++){
            n2=n2.next;
        }
        //将n2移到最后一个节点的下一个节点
        while (n2!=null){
            n1=n1.next;
            n2=n2.next;
        }
        //将3的next指向5
        n1.next=n1.next.next;
        return headNode.next;
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        System.out.println(removeNthFromEnd(listNode,2));
    }
}

